/*
 * @Description:
 * @Author: Rfan
 * @Date: 2021-10-29 22:59:41
 * @LastEditTime: 2022-07-16 17:29:43
 */

import { observable, action, runInAction } from 'mobx';
import { fetchAllUnit } from '@/api/units';
import { login, logout } from '@/api/userOpt';
import {
  getToken,
  getRealName,
  getUser,
  removeToken,
  setToken,
  setRealName,
  setUser,
  removeRealName,
  removeUser
} from '@/utils/auth';
import { getUnitId, setUnitId } from '@/utils/storage';
import { selectItemByKey } from '@/utils/list';

const langList = [
  { code: 'zh-CN', name: '简体中文', flag: 'flags/lang-zh-CN.jpg' },
  { code: 'en', name: 'English', flag: 'flags/lang-en.jpg' }
];

// 观察者
const appState = observable({
  realName: getRealName() || '',
  userInfo: getUser() || {},
  lang: navigator?.language || 'zh-CN',
  selectLangInfo: null,
  langList,
  formSchema: {},
  token: getToken(),
  tokenInfo: {},
  loginKey: '',
  ssid: '',
  unitId: getUnitId() || 0,
  unitList: [],
  isCollapse: false
});

// 方法
const appActions = {
  setUserName: action((name) => {
    appState.realName = name;
  }),

  clearUserName: action(() => {
    appState.realName = '';
  }),

  setLang: action((lang) => {
    appState.lang = lang;
    appState.selectLangInfo = selectItemByKey(lang, langList, 'code');
  }),

  setCollapse: action((collapse) => {
    appState.isCollapse = collapse;
  }),

  setFormSchema: action((schema) => {
    appState.formSchema = schema;
  }),

  /**
   * @description: 用户登录
   * @param {*} userInfo
   * @return {promise}
   */
  login: (userInfo) => {
    return new Promise((resolve, reject) => {
      userInfo.ssid = appState.ssid;
      login(userInfo)
        .then((res) => {
          const { data } = res;
          const { loginUser, loginUserDept, token } = data;
          const user = { ...loginUser, userDept: loginUserDept, userUnit: loginUserDept };
          runInAction(() => {
            appState.token = token.access_token;
            appState.realName = loginUser.realname;
            appState.userInfo = user;
            appState.unitId = loginUserDept.unitId;
          });
          setToken(token.access_token);
          setRealName(loginUser.realname);
          setUser(user);
          setUnitId(loginUserDept.unitId);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  /**
   * @description: 登出
   */
  logout() {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          action(() => {
            appState.token = '';
            appState.realName = '';
          });
          removeToken();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  /**
   * @description: 清楚token
   * @return {Promise}
   */
  resetToken() {
    return new Promise((resolve) => {
      action(() => {
        appState.token = '';
        appState.realName = '';
      });
      removeToken();
      removeRealName();
      removeUser();
      resolve();
    });
  },

  /**
   * @description: 设置公钥及ssid
   * @param {*} keyInfo publicKey与ssid
   */
  setPublicKey: action((keyInfo) => {
    appState.loginKey = keyInfo.publicKey;
    appState.ssid = keyInfo.ssid;
  }),

  /**
   * @description: 清除公钥及ssid
   */
  clearPublicKey: action(() => {
    appState.loginKey = '';
    appState.ssid = '';
  }),

  /**
   * @description: 设置全局单位ID
   */
  changeUnitId: action((id) => {
    appState.unitId = id;
    setUnitId(id);
  }),

  /**
   * @description: 设置全局单位ID
   */
  setUnitList: action((list) => {
    appState.unitList = list;
  }),

  /**
   * @description: 获取单位列表
   * @return {*}
   */
  getUnitList: () => {
    if (appState.token) {
      return new Promise((resolve, reject) => {
        fetchAllUnit({})
          .then((res) => {
            const _unitList = res.data;
            runInAction(() => {
              appState.unitList = _unitList;
            });
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};

export { appState, appActions };
